<?php

namespace addons\Minerva\backend\controllers;

use common\enums\AppEnum;
use common\enums\StatusEnum;
use common\enums\WhetherEnum;
use common\helpers\ArrayHelper;
use common\helpers\ResultHelper;
use common\models\rbac\AuthRole;
use Yii;
use addons\Minerva\common\models\MinervaDepartment;
use common\traits\Curd;
use common\models\base\SearchModel;
use yii\data\ActiveDataProvider;

/**
* MinervaDepartment
*
* Class DepartmentController
* @package addons\Minerva\backend\controllers
*/
class DepartmentController extends BaseController
{
    use Curd;

    /**
    * @var MinervaDepartment
    */
    public $modelClass = MinervaDepartment::class;

    /**
     * 默认应用
     *
     * @var string
     */
//    public $appId = AppEnum::BACKEND;

    /**
     * 权限来源
     *
     * false:所有权限，true：当前角色
     *
     * @var bool
     */
    public $sourceAuthChild = true;
    /**
     * 渲染视图前缀
     *
     * @var string
     */
    public $viewPrefix = '@addons/Minerva/backend/views/department/';

    /**
    * 首页
    *
    * @return string
    * @throws \yii\web\NotFoundHttpException
    */
    public function actionIndex()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => MinervaDepartment::find()
//                ->where(['app_id' => $this->appId])
//                ->andWhere(['>=', 'status', StatusEnum::DISABLED])
//                ->andFilterWhere(['merchant_id' => Yii::$app->services->merchant->getId()])
//                ->andFilterWhere(Yii::$app->services->rbacAuthRole->roleCondition($this->sourceAuthChild))
                ->orderBy('sort asc, created_at asc')
                ->asArray(),
            'pagination' => false
        ]);

        $role = $this->sourceAuthChild ? Yii::$app->services->rbacAuthRole->getRole() : [];

        return $this->render($this->viewPrefix . $this->action->id, [
            'dataProvider' => $dataProvider,
            'merchant_id' => $this->merchant_id,
            'role' => $role,
        ]);
    }

    /**
     * 编辑/创建
     *
     * @return mixed
     */
    public function actionEdit()
    {
        $id = Yii::$app->request->get('id', null);
        $model = $this->findModel($id);
        $model->pid = Yii::$app->request->get('pid', null) ?? $model->pid; // 父id
        $model->level = Yii::$app->request->get('level')+1;
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->referrer();
        }
//        $one_level = $model::find()->select(['id','title'])->indexBy('id')->asArray()->all();
        $one_level = $model::find()->asArray()->all();
        $list = ArrayHelper::removeByValue($one_level, $id);
        $models = ArrayHelper::itemsMerge($list);
        $data = ArrayHelper::map(ArrayHelper::itemsMergeDropDown($models), 'id', 'title');
        $dropDownList = ArrayHelper::merge([0 => '顶级部门'], $data);
//        echo '<pre>';
//        var_dump($dropDownList);die;

        return $this->render($this->action->id, [
            'model' => $model,
            'dropDownList' => $dropDownList
        ]);
    }

    /**
     * @return array|mixed
     * @throws \yii\db\Exception
     * @throws \yii\web\UnauthorizedHttpException
     */
//    public function actionEdit()
//    {
//        $id = Yii::$app->request->get('id', null);
////        $merchant_id = Yii::$app->services->merchant->getNotNullId();
//        /** @var AuthRole $model */
//        $model = $this->findModel($id);
//        $model->pid = Yii::$app->request->get('pid', null) ?? $model->pid; // 父id
////        $model->app_id = $this->appId;
//
//        if (Yii::$app->request->isPost) {
//            $data = Yii::$app->request->post();
//            $model->attributes = $data;
//            // 自动写入上级
////            if (
////                $this->sourceAuthChild &&
////                !Yii::$app->services->auth->isSuperAdmin() &&
////                empty($model->pid)
////            ) {
////                $role = Yii::$app->services->rbacAuthRole->getRole();
////                $model->pid = $role['id'];
////            }
//
//            if (!$model->save()) {
//                return ResultHelper::json(422, $this->getError($model));
//            }
//
////            // 创建角色关联的权限信息
////            Yii::$app->services->rbacAuthItemChild->accredit($model->id, $data['userTreeIds'] ?? [], WhetherEnum::DISABLED, $this->appId);
////            Yii::$app->services->rbacAuthItemChild->accredit($model->id, $data['plugTreeIds'] ?? [], WhetherEnum::ENABLED, $this->appId);
//
//            return ResultHelper::json(200, '提交成功');
//        }
//
//        // 获取所有权限还是当前已有的权限
////        if ($this->sourceAuthChild == true && !Yii::$app->services->auth->isSuperAdmin()) {
////            $role = Yii::$app->services->rbacAuthRole->getRole();
////            $allAuth = Yii::$app->services->rbacAuthItemChild->findItemByRoleId($role['id']);
////        } else {
////            $allAuth = Yii::$app->services->rbacAuthItem->findAll($this->appId);
////        }
//
////        list($defaultFormAuth, $defaultCheckIds, $addonsFormAuth, $addonsCheckIds) = Yii::$app->services->rbacAuthRole->getJsTreeData($id, $allAuth);
//
//        return $this->render($this->viewPrefix . $this->action->id, [
//            'model' => $model,
////            'defaultFormAuth' => $defaultFormAuth,
////            'defaultCheckIds' => $defaultCheckIds,
////            'addonsFormAuth' => $addonsFormAuth,
////            'addonsCheckIds' => $addonsCheckIds,
////            'dropDownList' => Yii::$app->services->rbacAuthRole->getDropDownForEdit($this->appId, $id),
////            'merchant_id' => $merchant_id
//        ]);
//    }

    /**
     * 获取上级角色
     *
     * 注意:如果是其他应用则需要自行获取上级
     *
     * @param $id
     * @return array
     */
    public function getDropDownForEdit($app_id, $id = '')
    {
        $list = $this->findAll($app_id, Yii::$app->services->merchant->getId());
        $list = ArrayHelper::removeByValue($list, $id);

        $models = ArrayHelper::itemsMerge($list);
        $data = ArrayHelper::map(ArrayHelper::itemsMergeDropDown($models), 'id', 'title');

        if (Yii::$app->services->auth->isSuperAdmin()) {
            return ArrayHelper::merge([0 => '顶级角色'], $data);
        }

        return $data;
    }
}
